<template>
  <div class="file-preview-container">
    <!-- 错误状态 -->
    <div v-if="isError" class="preview-error">
      <el-icon>
        <Picture />
      </el-icon>
      <span>文件加载失败: {{ error }}</span>
    </div>

    <!-- 正常预览 -->
    <div v-else class="preview-content" v-loading="loading" element-loading-text="预览加载中…请稍后…">

      <!-- 图片预览 -->
      <div v-if="isImage" class="image-preview">
        <img :src="filePath" alt="" class="preview-image">
        <!-- <el-image :src="filePath" fit="contain" :preview-src-list="[filePath]" @load="handleImageLoad"
          @error="handleError" class="preview-image" /> -->
      </div>

      <!-- PDF 预览 -->
      <vue-office-pdf v-else-if="isPdf" :src="filePath" @rendered="handleRendered" @error="handleError"
        class="preview-component" />

      <!-- Word 预览 -->
      <vue-office-docx v-else-if="isDoc" :src="filePath" @rendered="handleRendered" @error="handleError"
        class="preview-component" />

      <!-- Excel 预览 -->
      <vue-office-excel v-else-if="isExcel" :src="filePath" @rendered="handleRendered" @error="handleError"
        class="preview-component" />

      <!-- 未知文件类型 -->
      <div v-else class="unknown-type">
        暂不支持预览该类型文件（当前类型: {{ fileType }})
      </div>
    </div>
  </div>
</template>

<script setup>
import { Picture } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus'
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import VueOfficePdf from '@vue-office/pdf';
import '@vue-office/docx/lib/index.css'
import '@vue-office/excel/lib/index.css'

// 定义 props
const props = defineProps({
  fileType: {
    type: String,
    required: true
  },
  filePath: {
    type: String,
    required: true,
    default: ""
  },
  isImage: {
    type: Boolean,
    default: false
  }
});

// 定义事件
const emit = defineEmits(['rendered', 'error', 'loading']);

// 状态管理
const loading = ref(false);
const error = ref('');
const isError = ref(false)

// 计算属性：判断文件类型
const isPdf = computed(() => props.fileType === 'pdf');
const isDoc = computed(() => ['docx'].includes(props.fileType));
const isExcel = computed(() => ['xlsx'].includes(props.fileType))

// 组件挂载前初始化
onBeforeUnmount(() => {
  if (props.filePath && props.filePath.startsWith('blob:')) {
    URL.revokeObjectURL(props.filePath);
  }
});
// 图片加载完成处理函数
const handleImageLoad = () => {
  loading.value = false;

  // 强制重新渲染组件或清除缓存
  // nextTick 是必要的，确保 DOM 更新后再执行
  nextTick(() => {
    // 可以尝试强制重新设置一些相关值
    const imgElement = document.querySelector('.preview-image');
    if (imgElement) {
      imgElement.style.display = 'block';
    }
  });
};

// 渲染完成回调
const handleRendered = () => {
  loading.value = false;
};

// 添加错误锁定状态
const errorLocked = ref(false);
// 错误处理回调
const handleError = (err) => {
  if (err.message !== 'src属性不能为空') {
    console.log("错误回调", err);
    loading.value = false;
    const errorMessage = err.message || '未知错误'
    error.value = errorMessage + "，请下载查看";
  }
  // loading.value = false;
  // const errorMessage = err.message || '未知错误';

  // 锁定错误状态，防止被立即覆盖
  // errorLocked.value = true;

  // nextTick(() => {
  // error.value = errorMessage + "，请下载查看";
  // isError.value = true;
  // ElMessage.error(errorMessage);

  // 设置定时器，在一定时间后解锁错误状态
  // setTimeout(() => {
  //   errorLocked.value = false;
  // }, 3000);
  // });
};
const currentLoadingSource = ref(null)
// 监听文件路径变化
watch(() => props.filePath, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    error.value = '';
    isError.value = false;
    loading.value = false;
    // 只有在没有锁定错误时才清空错误状态
    // if (!errorLocked.value) {
    //   error.value = '';
    // }
    if (newVal.endsWith('empty') || newVal.includes('null')) {
      error.value = '文件内容为空，请重新上传';
      loading.value = false;
      isError.value = true;
      return;
    }
    currentLoadingSource.value = props.isImage ? 'image' : 'document';
    if (props.isImage || isDoc.value || isExcel.value || isPdf.value) {
      loading.value = true; // 只有支持的文件类型才显示加载状态
    }
    if (props.isImage) {
      // 创建一个新的 Image 对象并手动处理加载事件
      const img = new Image();
      img.onload = () => {
        if (currentLoadingSource.value === 'image') {
          handleImageLoad();
        }
      };
      img.onerror = (e) => {
        if (currentLoadingSource.value === 'image') {
          handleError(new Error('图片加载失败'));
        }
      };
      img.src = newVal;
    }
  }
}, { immediate: true });

// watch(() => error.value, (newVal, oldVal) => {
//   console.group(`[错误状态变化]`)
//   console.log('旧值:', oldVal)
//   console.log('新值:', newVal)
//   console.log('锁定状态:', errorLocked.value)
//   console.groupEnd()
// })
</script>

<style lang="scss" scoped>
.file-preview-container {
  width: 100%;
  height: calc(100vh - 155px);
  min-height: 400px;
  position: relative;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;

  .preview-loading,
  .preview-error,
  .unknown-type {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    color: #606266;
    position: absolute;
  }

  .preview-content {
    width: 100%;
    height: 100%;
    position: relative;
  }

  .preview-loading {
    color: #409eff;
  }

  .preview-error {
    color: #f56c6c;
  }

  .preview-component {
    width: 100%;
    height: calc(100vh - 150px);
  }

  .image-preview {
    width: 100%;
    height: calc(100vh - 150px);
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f5f5;
    overflow: auto;

    .preview-image {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  }

  .unknown-type {
    height: 200px;
    font-size: 14px;
  }
}
</style>